package com.doubao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.entity.SmartDeviceTag;
import com.doubao.entity.SmartDeviceTagRelation;
import com.doubao.exception.BusinessException;
import com.doubao.entity.SmartDevice;
import com.doubao.entity.UserDeviceCollection;
import com.doubao.entity.dto.SmartDeviceCreateDTO;
import com.doubao.entity.vo.SmartDeviceVO;
import com.doubao.mapper.SmartDeviceMapper;
import com.doubao.mapper.SmartDeviceTagMapper;
import com.doubao.mapper.SmartDeviceTagRelationMapper;
import com.doubao.mapper.UserDeviceCollectionMapper;
import com.doubao.service.SmartDeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.collection.CollUtil;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SmartDeviceServiceImpl extends ServiceImpl<SmartDeviceMapper, SmartDevice> implements SmartDeviceService {

    private final UserDeviceCollectionMapper collectionMapper;
    private final SmartDeviceTagMapper tagMapper; // 新增 tagMapper 字段
    private final SmartDeviceTagRelationMapper tagRelationMapper; // 新增 tagRelationMapper 字段

     @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceTags(Long deviceId, List<String> tagNames) {
        // 删除原有标签关联
        tagRelationMapper.deleteByDeviceId(deviceId);

        // 保存新标签
        if (CollUtil.isNotEmpty(tagNames)) {
            saveDeviceTags(deviceId, tagNames);
        }
    }

    @Override
    public List<String> getDeviceTags(Long deviceId) {
        return tagMapper.selectDeviceTags(deviceId)
                .stream()
                .map(SmartDeviceTag::getName)
                .collect(Collectors.toList());
    }

    @Override
    public List<SmartDeviceTag> getHotTags(int limit) {
        return tagMapper.selectHotTags(limit);
    }

    /**
     * 获取或创建标签
     */
    private SmartDeviceTag getOrCreateTag(String tagName) {
        SmartDeviceTag tag = tagMapper.selectOne(
                new LambdaQueryWrapper<SmartDeviceTag>()
                        .eq(SmartDeviceTag::getName, tagName)
        );

        if (tag == null) {
            tag = new SmartDeviceTag();
            tag.setName(tagName);
            tagMapper.insert(tag);
        }

        return tag;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SmartDevice createDevice(SmartDeviceCreateDTO dto, Long userId) {
        // 校验数量限制
        checkDeviceLimit(userId);

        // 创建智能体
        SmartDevice device = new SmartDevice();
        BeanUtils.copyProperties(dto, device);
        device.setUserId(userId);
        device.setType(0);
        device.setCollectCount(0);
        device.setChatCount(0);
        device.setModelEndpointId("doubao-pro-32k");
        save(device);

        // 处理标签
        if (CollUtil.isNotEmpty(dto.getTags())) {
            saveDeviceTags(device.getId(), dto.getTags());
        }

        return device;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void collectDevice(Long userId, Long deviceId) {
        SmartDevice device = getById(deviceId);
        if (device == null || device.getVisibility() == 0) {
            throw new BusinessException("智能体不存在或不可见");
        }

        // 检查是否已收藏
        boolean exists = collectionMapper.exists(
                new LambdaQueryWrapper<UserDeviceCollection>()
                        .eq(UserDeviceCollection::getUserId, userId)
                        .eq(UserDeviceCollection::getDeviceId, deviceId)
        );

        if (!exists) {
            // 添加收藏
            UserDeviceCollection collection = new UserDeviceCollection();
            collection.setUserId(userId);
            collection.setDeviceId(deviceId);
            collection.setStatus(1);
            collectionMapper.insert(collection);

            // 更新收藏计数
            lambdaUpdate()
                    .setSql("collect_count = collect_count + 1")
                    .eq(SmartDevice::getId, deviceId)
                    .update();
        }
    }

// SmartDeviceServiceImpl.java 继续
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void uncollectDevice(Long userId, Long deviceId) {
        // 更新收藏状态
        int rows = collectionMapper.updateCollectionStatus(userId, deviceId, 0);

        if (rows > 0) {
            // 更新收藏计数
            lambdaUpdate()
                    .setSql("collect_count = collect_count - 1")
                    .eq(SmartDevice::getId, deviceId)
                    .update();
        }
    }

    @Override
    public List<SmartDeviceVO> listUserDevices(Long userId) {
        return baseMapper.selectUserDevices(userId);
    }

   @Override
   public IPage<SmartDeviceVO> pagePublicDevices(Page<SmartDevice> page, String category) {
       // 假设需要传入的第三个参数是 userId，可以根据实际情况调整
       Long userId = 1L; // 示例值，实际应用中应从请求或其他地方获取
       return baseMapper.selectPublicDevices(page, userId, category);
   }


    @Override
    public void checkDeviceAccess(Long userId, Long deviceId) {
        SmartDevice device = getById(deviceId);
        if (device == null) {
            throw new BusinessException("智能体不存在");
        }

        // 创建者可访问
        if (device.getUserId().equals(userId)) {
            return;
        }

        // 公开的智能体可访问
        if (device.getVisibility() == 1) {
            return;
        }

        // 检查是否收藏了私密智能体
        boolean collected = collectionMapper.exists(
                new LambdaQueryWrapper<UserDeviceCollection>()
                        .eq(UserDeviceCollection::getUserId, userId)
                        .eq(UserDeviceCollection::getDeviceId, deviceId)
                        .eq(UserDeviceCollection::getStatus, 1)
        );

        if (!collected) {
            throw new BusinessException("无权访问该智能体");
        }
    }

    /**
     * 校验用户智能体数量限制
     */
   private void checkDeviceLimit(Long userId) {
       long count = lambdaQuery()
               .eq(SmartDevice::getUserId, userId)
               .count();
       if (count >= 10) {
           throw new BusinessException("最多只能创建10个智能体");
       }
   }


    /**
     * 保存智能体标签
     */
    private void saveDeviceTags(Long deviceId, List<String> tagNames) {
        for (String tagName : tagNames) {
            // 获取或创建标签
            SmartDeviceTag tag = tagMapper.selectOne(
                    new LambdaQueryWrapper<SmartDeviceTag>()
                            .eq(SmartDeviceTag::getName, tagName)
            );
            if (tag == null) {
                tag = new SmartDeviceTag();
                tag.setName(tagName);
                tagMapper.insert(tag);
            }

            // 建立关联关系
            SmartDeviceTagRelation relation = new SmartDeviceTagRelation();
            relation.setDeviceId(deviceId);
            relation.setTagId(tag.getId());
            tagRelationMapper.insert(relation);
        }
    }
}